// ROT13_Encode.cpp
// Implementation of the ROT13 encoding routine
// Michael Coles, MCDBA, 7/2005
//
#include "stdafx.h"
#include "ROT13_Encode.h"

// The number of letters in the alphabet.
#define NUM_LETTERS		26

// This function encodes a plain text string using ROT13
//
// Parameters:
//		BYTE *pPlainText	is a pointer to the plain text string.
//		BYTE *pROT13Text	is a pointer to the ROT13 encoded string.
//		ULONG length		is the length of the plain text string.
//
void ROT13_Encode_String(BYTE *pPlaintext, 
						 BYTE *pROT13Text,
						 ULONG length) {
	// Loop through each plain text character and assign the ROT13-encoded character
	// in the ROT13-encoded string.
	for (ULONG i = 0; i < length; i++) {
		*(pROT13Text + i) = ROT13_Encode_Char(*(pPlaintext + i));
	}
};

// This function encodes a plain text character using ROT13.  Only characters between
// 'A' - 'Z', or 'a' - 'z', are encoded using ROT13.  All other characters are left
// exactly the same.
//
// Parameters:
//		BYTE c		is a plain text character.
// Returns:
//		BYTE		the return value is the ROT-13 encoded character.
//
BYTE ROT13_Encode_Char(BYTE c) {
	// If the character is between 'A' and 'Z', or 'a' and 'z', we perform the following
	// encoding steps:
	//
	//		1.	Subtract 'A' (or 'a' for lowercase), giving us the position number of the
	//			character in the alphabet, A = 0, Z = 25.
	//		2.	We add 1/2 of the Number of Characters in the alphabet (13).
	//		3.	We take this value modulo the Number of Characters in the alphaber (26).
	//			This ensures that we stay within the range of 'A' - 'Z' (or 'a' - 'z') 
	//			and that we get that all-important wrap-around effect that comes from
	//			having an even number of letters in our alphabet.
	//		4.	We add back in 'A' ('a' for lowercase) to get back out printable
	//			alphabetic character.
	//
	if (c >= 'A' && c <= 'Z') {
		c = (((c - 'A') + (NUM_LETTERS / 2)) % NUM_LETTERS) + 'A';
	} else if (c >= 'a' && c <= 'z') {
		c = (((c - 'a') + (NUM_LETTERS / 2)) % NUM_LETTERS) + 'a';
	}
	return (c);
};